// lib/api/auth_api.dart
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/response.dart';
import '../models/user.dart';
import '../utils/app_constants.dart';
import 'dio_client.dart';

class AuthApi {
  final Dio _dio = DioClient().dio; // 获取 Dio 单例

  /// 用户注册 (保持不变)
  Future<ResponseSuccess<User>> signup({
    required String username,
    required String password,
    required String rePassword,
    required String phone,
  }) async {
    try {
      final response = await _dio.post(
        '/signup', // 注册 API 路径
        data: {
          'username': username,
          'password': password,
          're_password': rePassword,
          'phone': phone,
        },
      );
      return ResponseSuccess.fromJson(response.data, (json) => User.fromJson(json as Map<String, dynamic>));
    } on DioException catch (e) {
      throw e.response?.data['msg'] ?? '注册失败，请稍后再试。';
    } catch (e) {
      throw '注册发生未知错误: $e';
    }
  }

  /// 用户登录
  Future<ResponseSuccess<User>> login({
    required String username,
    required String password,
  }) async {
    try {
      final response = await _dio.post(
        '/login', // 登录 API 路径
        data: {
          'username': username,
          'password': password,
        },
      );
      final successResponse = ResponseSuccess.fromJson(response.data, (json) => User.fromJson(json as Map<String, dynamic>));

      // 登录成功后保存 Token
      if (successResponse.code == 1000 && successResponse.data?.token != null) {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(AppConstants.tokenKey, successResponse.data!.token!);
        print('Token 已保存: ${successResponse.data!.token!}');

        // **修改这里：从 successResponse.data.username 获取用户名**
        if (successResponse.data?.username != null && successResponse.data!.username.isNotEmpty) {
          await prefs.setString('current_username', successResponse.data!.username);
        } else {
          // 如果后端返回的 user_name 字段没有映射到 username，可以尝试直接从原始 response.data 中获取
          // 但这种方式不推荐，因为它绕过了模型解析
          // if (response.data['data'] != null && response.data['data']['user_name'] != null) {
          //   await prefs.setString('current_username', response.data['data']['user_name']);
          // }
          print('警告：User 模型中的 username 为空或为null');
        }
      }
      return successResponse;
    } on DioException catch (e) {
      throw e.response?.data['msg'] ?? '登录失败，请检查用户名或密码。';
    } catch (e) {
      throw '登录发生未知错误: $e';
    }
  }

  /// 用户退出登录（清除 Token） (保持不变)
  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(AppConstants.tokenKey);
    print('Token 已清除。');
  }
}